package com.zto.wk.webflux.controller;

import com.zto.wk.webflux.message.EchoMessage;
import com.zto.wk.webflux.user.UserManager;
import com.zto.wk.webflux.user.UserSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.reactive.socket.WebSocketSession;

import java.util.Map;

/**
 * Created by wangkuan at 2018-08-13 15:38
 */
@Controller
public class WebsocketClientController {
    @Autowired
    private UserManager userManager;

    @RequestMapping(value = "client", method = RequestMethod.GET)
    public String websocketClient() {
        return "websocket-client";
    }

    @RequestMapping("user/list")
    public ResponseEntity<Map<String, String>> getUserMap() {
        return ResponseEntity.ok(userManager.getNameMap());
    }

    @RequestMapping("send")
    public ResponseEntity<String> send(EchoMessage message) {
        String result;

        UserSession userSession = userManager.get(message.getSendTo());
        if (userSession == null || userSession.getWebSocketSession() == null) {
            result = "找不到对方，无法发送消息";
        } else {
            WebSocketSession session = userSession.getWebSocketSession();
            session.send(session.receive()
                    .map(msg -> session.textMessage(message.getFromUser() + " : " + message.getContent())));

            result = "发送消息成功";
        }

        return ResponseEntity.ok(result);
    }

}
